﻿(function ($) { 
    // 汉字转拼音
    $.fn.convertPinyin = function (type) {  //type 1汉字全拼  2 汉字首字母小写  3 汉字首字母大写

        var _this = $(this);
        var l1 = _this.val();
        var l2 = l1.length;
        var I1 = "";
        var reg = new RegExp('[a-zA-Z0-9\- ]');
        for (var i = 0; i < l2; i++) {
            var val = l1.substr(i, 1);
            var name = _this.arraySearch(val, PinYin);
            if (reg.test(val)) {
                switch (type) {
                    case 1://默认返回为全拼
                        break;
                    case 2://汉字首字母小写
                        val = val.toLowerCase();
                        break;
                    case 3:
                        val = val.toUpperCase();
                        break;
                }
                I1 += val;
            } else if (name !== false) {
                switch (type) {
                    case 1://默认返回为全拼
                        break;
                    case 2://汉字首字母小写
                        name = name.substr(0, 1).toLowerCase();
                        break;
                    case 3:
                        name = name.substr(0, 1).toUpperCase();
                        break;
                }
                I1 += name;
            }
        }
        I1 = I1.replace(/ /g, '-');
        while (I1.indexOf('--') > 0) {
            I1 = I1.replace('--', '-');
        }
        return I1;
    };
    $.fn.arraySearch = function (l1, l2) {
        var _this = $(this);
        for (var name in PinYin) {
            if (PinYin[name].indexOf(l1) > -1) {
                return _this.ucfirst(name);
            }
        }
        return false;
    };
    $.fn.ucfirst = function ucfirst(l1) {
        if (l1.length > 0) {
            var first = l1.substr(0, 1).toUpperCase();
            var spare = l1.substr(1, l1.length);
            return first + spare;
            // return first;
        }
    };
    $.fn.isEmpty = function () {
        var val = $(this).val();
        if (val === "")
            return false;
        else
            return true;
    };
    $.fn.fullPinyin = function (item) {
        var _this = $(this);
        var val = _this.convertPinyin(1);
        var pinyin = "";
        if (val.indexOf('-') == -1) {
            pinyin = val;
        }
        $(item).val(pinyin).text(pinyin);
    };
    $.fn.initialLower = function (item) {
        var _this = $(this);
        var val = _this.convertPinyin(2);
        var pinyin = "";
        if (val.indexOf('-') == -1) {
            pinyin = val;
        } 
        $(item).val(pinyin).text(pinyin);
    };
    $.fn.initialUpper = function (item) {
        var _this = $(this);
        var val = _this.convertPinyin(3);
        var pinyin = "";
        if (val.indexOf('-') == -1) {
            pinyin = val;
        }       
        $(item).val(pinyin).text(pinyin);
    };
})(jQuery);
 
// 首字母大写
